<template>
    <el-image-viewer v-if="viewerVisible2" :url-list="HignSpeedUrls" :initial-index="imgcurrentIndex"
        @close="closeViewerimg" />
    <div v-loading="loading">
        <!-- 用户导入对话框 -->
        <el-upload v-model:file-list="fileList" ref="uploadRef" accept=".jpg,.jpeg,.png" :action="uploadFileUrl"
            :headers="headers" :multiple="true" :show-file-list="false" :before-upload="beforeUpload"
            :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="true"
            :data="uploadData">
            <el-button type="primary" :disabled="isbackmsg">
                <el-icon class="me-2">
                    <Plus />
                </el-icon>
                上传文书
            </el-button>
            <template #tip>
                <div class="el-upload__tip">
                    请上传<span style="color: red;"> .jpg , .jpeg , .png </span> 格式图片
                </div>
            </template>
        </el-upload>
        <el-image-viewer v-if="viewerVisible" :url-list="srcList" @close="closeViewer" />
        <el-table :data="SecurityChecktableData" show-overflow-tooltip class="mt-3" border>
            <el-table-column prop="filename" label="文件名称" />
            <!-- <el-table-column prop="type" label="文书类型" min-width="120" /> -->
            <el-table-column prop="fileurl" label="保存地址" />
            <el-table-column fixed="right" label="操作" width="140" align="center">
                <template #default="scope">
                    <el-button link type="primary" size="small" @click="getImageInfo(scope.row)">
                        <el-icon class="me-1">
                            <View />
                        </el-icon>
                        详情
                    </el-button>
                    <el-button link type="danger" size="small" @click="remove(scope.row)">
                        <el-icon class="me-1">
                            <Delete />
                        </el-icon>
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-col :span="24" class="mb-5 mt-4">
            <!-- <el-row style="width: 100%;">
                <el-col :span="24">
                    <el-button type="primary" @click="HighSpeedBtn" :disabled="isbackmsg">高拍仪</el-button>
                </el-col>
                <el-col :span="24" class="mt-4"> -->
            <el-row style="width: 100%;">
              <el-col :span="10" >
                <el-button v-if="isopenCameraBtn"  type="primary" @click="CameraBtn" class='mb-3'>
                    启动摄像头
                </el-button>
                <el-button v-else type="danger" @click="CloseCameraBtn" class='mb-3'>
                    关闭摄像头
                </el-button>
                <!-- <el-button   type="primary" @click="CameraBtn" class='mb-3'>
                    启动摄像头
                </el-button>
                <el-button  type="danger" @click="CloseCameraBtn" class='mb-3'>
                    关闭摄像头
                </el-button> -->
              </el-col>
              <el-col :span="6">
                <el-button v-if="!isopenCameraBtn" type="primary" @click="SaveCameraBtn" class='mb-3'>
                    拍照
                </el-button>
              </el-col>
              <el-row style="width: 100%;">
                  <el-col :span="22">
                      <div style="width: 422px;height: 302px;border: 1px solid #666666; background: #fff">
                          <canvas ref="videoCanvas" width="420" height="300"></canvas>
                      </div>
                  </el-col>
              </el-row>
              <el-col :span="24" style="display: flex;flex-wrap: wrap;">
                <div class="block" style="width: 110px; height: 110px;position: relative;margin-right: 10px;"
                    v-for="(img, index) in HignSpeedUrls"  @click="clickImage(index)"
                    :key="index">
                  <el-image style="width: 110px; height: 110px;position: relative;"
                    :src="img"
                    fit="contain" 
                    >
                      <template #error>
                          <div class="image-slot">
                              请使用高拍仪
                          </div>
                      </template>
                  </el-image>
                  <el-icon class="me-1 edit-icon" @click="deletHighSpeedImg(index, $event)">
                      <circle-close />
                  </el-icon>
                </div>
              </el-col>
            </el-row>
          <!-- </el-col>
            </el-row> -->
        </el-col>
        <el-row class="mb-3 mt-3" style="text-align:right">
            <el-col :span="24">
                <el-button type="" @click="Reset">
                    <el-icon class="me-2">
                        <Refresh />
                    </el-icon>
                    刷新
                </el-button>
                <el-button type="primary" @click="SaveAll">
                    <el-icon class="me-2">
                        <Plus />
                    </el-icon>
                    全部保存
                </el-button>

            </el-col>
        </el-row>
    </div>
</template>
<script setup>
import { ElMessage } from 'element-plus'
import { getCurrentInstance, onMounted, ref } from "vue";
import { ElMessageBox } from 'element-plus'
const { proxy } = getCurrentInstance()
import { docList, imageInfo, saveUploadFile, delUploadFile, SignuploadFile, SignDelFile, SignList, SignimageInfo, } from "@/api/ApplyDetail/ApplyDetail";
import { getToken } from "@/utils/auth";
import { getPoliceAreaInfo } from "@/api/PoliceAreaManage/PoliceAreaManage";
import md5 from 'js-md5'
import { ElImageViewer } from 'element-plus'
import { WebSocketService } from "@/utils/websocket";  // 导入 WebSocket 服务
const props = defineProps({
    data: {
        type: Object,
        required: true, // 如果这个属性是必需的
    },
})
const isbackmsg = ref(false)
const loading = ref(false)

// WebSocket 服务实例
let webSocketService = null;
const websocketUrl = ref()

const HignSpeedUrls = ref([])
const HignSpeedSubUploadID = ref([])
const fileList = ref([])
const srcList = ref([])
const viewerVisible = ref(false)

const fileType = ref('')

const isopenCameraBtn = ref(true) // 摄像头按钮是否显示

// 新增帧率控制相关变量
const targetFPS = 20; // 目标帧率(可根据需要调整)1秒15帧。可以调整，越高越流畅，但是对内存及  Gpu要求越高
const frameInterval = 1000 / targetFPS; // 每帧间隔(ms)
let lastRenderTime = 0; // 上次渲染时间戳
let frameQueue = []; // 帧队列(最多保留1帧)
let isRendering = false; // 是否正在渲染中
let animationFrameId = null; // requestAnimationFrame ID


const videoCanvas = ref(null); // Canvas DOM 引用
const canvasCtx = ref(null);   // Canvas 2D 上下文

const viewerVisible2 = ref(false)
const imgcurrentIndex = ref(0);
const isHighSpeedValue = ref()


// 用于预览
const clickImage = (index) => {
    imgcurrentIndex.value = index
    setTimeout(() => {
        viewerVisible2.value = true;
    }, 100);
};
// 用于关闭预览
const closeViewerimg = () => {
    viewerVisible2.value = false;
};

const SecurityChecktableData = ref([{}])
const DutyRecordRef = ref({})
const queryParams = ref({
})

// 额外参数（这里是携带 jwApplyDetailId）
const uploadData = ref({
    jwApplyDetailId: '',  // 设置你的 jwApplyDetailId 值
    md5key: ''
});

const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + "/bussiness/ApplyDetail/uploadFile")
const headers = ref({
    Authorization: "Bearer " + getToken()
});
const paging = ref({
    // 页码
    pageNum: 1,
    // 分页数量
    pageSize: 10
})

onMounted(() => {
    window.addEventListener('beforeunload', cleanup);
    nextTick(() => {
    if (videoCanvas.value) {
        canvasCtx.value = videoCanvas.value.getContext('2d');
        videoCanvas.value.width = 420;
        videoCanvas.value.height = 300;
        console.log("Canvas初始化完成，尺寸:", videoCanvas.value.width, "x", videoCanvas.value.height);
      } else {
        console.error("Canvas元素未找到！");
      }
  })
    if (props.data && props.data.jw_applydetail_id) {
        uploadData.value.jwApplyDetailId = props.data.jw_applydetail_id
        // 调用接口获取列表数据
        queryParams.value.objectId = props.data.jw_applydetail_id
        queryParams.value.type = '1'
        getLists();
        getPoliceAreaInfos(props.data)
    }
})

// 获取列表
const getLists = async () => {
    loading.value = true
    await docList(queryParams.value).then(res => {
        SecurityChecktableData.value = res.data
        loading.value = false
    })
}
// 获取办案区ip地址
const getPoliceAreaInfos = async (querydata) => {
    getPoliceAreaInfo(querydata.policearea_id).then(res => {
        websocketUrl.value = 'ws://' + res.data.ipAddress + ':' + res.data.port
        // 创建 WebSocket 实例
        webSocketService = new WebSocketService(websocketUrl.value);
        // webSocketService = new WebSocketService('ws://192.168.3.34:18887');

        // 启动 WebSocket 连接
        webSocketService.createWebSocket()
            .then(() => {
                const path = window.location.pathname
                const istrue =  path.includes('/PoliceWork/')
                if(istrue){
                //     ElMessage.success({
                //     message: '与终端设备连接成功',
                //     showClose: true,
                // })
                }
            })
            .catch((error) => {

            });

        // 设置接收到消息时的回调
        webSocketService.setOnMessageCallback(handleWebSocketMessage);
    })
}
// 全部保存
const SaveAll = async () => {
    const jwUploadIdsArr = SecurityChecktableData.value.map(item => item.jwUploadId);
    if (jwUploadIdsArr.length == 0) {
        return
    } else {
        loading.value = true
        await saveUploadFile(jwUploadIdsArr).then(res => {
            // proxy.$modal.msgSuccess(`保存成功`)
            // ElMessage.success({
            //     message: '保存成功',
            //     // showClose: true,
            //     grouping: true,
            // })
            loading.value = false
        })
    }

}
const Reset = async () => {
    getLists()
}
// 发送消息
function SendMes() {
    webSocketService.sendMessage(2)        //1是签名，2是高拍仪，3是身份证
}

// 点击启动摄像头
function CameraBtn() {
  console.log(webSocketService.ws.readyState,'webSocketService.ws.readyState')
    if(webSocketService.ws.readyState == 1){
      SendMes()
      isopenCameraBtn.value = false // 摄像头按钮是否显示
    }else{
      // 创建 WebSocket 实例
      webSocketService = new WebSocketService(websocketUrl.value);
    //   webSocketService = new WebSocketService('ws://192.168.3.34:18887');
      // 启动 WebSocket 连接
      webSocketService.createWebSocket()
        .then(() => {
          ElMessage.success({
            message: '与终端设备连接成功',
            showClose: true,
          })
          // 设置接收到消息时的回调
          webSocketService.setOnMessageCallback(handleWebSocketMessage);
          // 发送消息
          SendMes()
          isopenCameraBtn.value = false // 摄像头按钮是否显示
        })
        .catch((error) => {
          // proxy.$modal.error(`WebSocket 连接失败: ${error.message}`);
        });
    }
}
// 点击关闭摄像头{
    function CloseCameraBtn() {
    webSocketService.sendMessage('closeCamera')
    isopenCameraBtn.value = true // 摄像头按钮是否显示
    // 清空画布
    clearCanvas();
}
// 清空画布的函数
function clearCanvas() {
  if (canvasCtx.value && videoCanvas.value) {
    console.log("清空画布")
    // 清除整个画布
    // 强制重绘（备用方案）
    if (canvasCtx.value) {
      canvasCtx.value.clearRect(0, 0, 
        videoCanvas.value.width, 
        videoCanvas.value.height);
    }
    // 可选：填充白色背景（如果需要）
      canvasCtx.value.fillStyle = '#ffffff';
      canvasCtx.value.fillRect(0, 0, videoCanvas.value.width, videoCanvas.value.height);
  }
}
// 点击保存图片
async function SaveCameraBtn() {
  webSocketService.sendMessage(11) // 1是签名，2是高拍仪，3是身份证
}
// const HighSpeedBtn = async () => {
//     // 判断浏览器是否支持 WebSocket
//     isbackmsg.value = true
//         if (webSocketService) {
//             SendMes()
//         } else {
//             /// 创建 WebSocket 实例
//             webSocketService = new WebSocketService(websocketUrl.value);

//             // 启动 WebSocket 连接
//             webSocketService.createWebSocket()
//                 .then(() => {
//                     const path = window.location.pathname
//                     const istrue =  path.includes('/PoliceWork/')
//                     if(istrue){
//                         ElMessage.success({
//                         message: '与终端设备连接成功',
//                         showClose: true,
//                     })
//                     }
//                     // 发送消息
//                     SendMes()
//                 })
//                 .catch((error) => {
//                     // proxy.$modal.error(`WebSocket 连接失败: ${error.message}`);
//                 });
//             // 设置接收到消息时的回调
//             webSocketService.setOnMessageCallback(handleWebSocketMessage);
//         }
//     } 
// 处理 WebSocket 消息
function handleWebSocketMessage(message) {
    isbackmsg.value = false
    if (message === 'cancel' || message === 'end') {
        proxy.$modal.msgWarning(`用户${message === 'cancel' ? '取消' : '结束'}了操作`);
        return;
    }
    if(typeof message === 'string'){
        try {
            const data = JSON.parse(message);
            if (data.photo) {
                // 处理拍照结果...
                // 创建Base64图片URL
              const imgUrl = `data:image/jpeg;base64,${data.photo}`;
              // 将图片URL添加到HignSpeedUrls数组
              HignSpeedUrls.value.push(imgUrl);
              // 2. 转成 Blob（base64 => binary）
              const byteString = atob(data.photo);
              const arrayBuffer = new ArrayBuffer(byteString.length);
              const uint8Array = new Uint8Array(arrayBuffer);
              for (let i = 0; i < byteString.length; i++) {
                  uint8Array[i] = byteString.charCodeAt(i);
              }
              const blob = new Blob([uint8Array], { type: 'image/jpeg' });

              // 3. 准备上传参数
              const query = {
                  jwApplyDetailId: props.data.jw_applydetail_id,
                  md5key: '12313',
                  fileType: '1' // 2人员进入高拍仪
              };

              const formData = new FormData();
              formData.append('file', blob, 'capture.jpg');

              // 4. 调用上传接口
              SignuploadFile(formData, query).then(res => {
                  proxy.$modal.msgSuccess(`照片上传成功`);
                  HignSpeedSubUploadID.value.push(res.msg);
                  getLists().then(() => {
                        SaveAll();
                    });
              });
            }
            return; // 拍照逻辑结束后直接返回
            } catch (e) {
                console.warn("非JSON消息:", message);
            }
    }
    // 情况2：视频流的Blob数据
    if (message instanceof Blob) {
        if (frameQueue.length > 0) {
            frameQueue[0] = message;
        } else {
            frameQueue.push(message);
        }
        scheduleRender();
    }
    //     let imgUrl = ''
    //     imgUrl = URL.createObjectURL(message);
    //     HignSpeedUrls.value.push(imgUrl);
    //     const query = {
    //         jwApplyDetailId: props.data.jw_applydetail_id,
    //         md5key: '12313',
    //         fileType: '1'                   //  2人员进入高拍仪 3体检高拍仪 4体检医生签名 5体检涉案人签名
    //     }
    //     const formData = new FormData();
    //     formData.append('file', message, 'image.png');  // 这里的 'image.png' 是文件名，你可以根据需要修改
    //     // 6. 调用接口进行上传
    //     SignuploadFile(formData, query).then(res => {
    //         ElMessage.success({
    //             message: '上传成功',
    //             // showClose: true,
    //             grouping: true,
    //         })
    //         HignSpeedSubUploadID.value.push(res.msg);
    //         getLists().then(() => {
    //             SaveAll();
    //         });
    //     })
    // }

}
// 获取详情
const getImageInfo = async (row) => {
    loading.value = true
    fileType.value = row.filename.split('.')[1]
    // 调用接口获取图片详情
    await imageInfo(row.jwUploadId).then(res => {
        loading.value = false
        const blob = new Blob([res], { type: 'image/' + fileType.value });
        const BlobUrlListData = URL.createObjectURL(blob);
        srcList.value = [BlobUrlListData]; // 创建 URL
        viewerVisible.value = true
    })
}
// 用于关闭预览
const closeViewer = () => {
    srcList.value = [];
    viewerVisible.value = false;
};
// 删除
const remove = async (row) => {
    ElMessageBox.confirm('确定删除此文件？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        loading.value = true
        delUploadFile(row.jwUploadId).then(res => {
            // 找到 HignSpeedSubUploadID.value 中与 row.jwUploadId 相等的索引
            const indexToDelete = HignSpeedSubUploadID.value.findIndex(id => id == row.jwUploadId);
            if (indexToDelete != -1) {
                // 删除 HignSpeedUrls.value 中对应索引的值
                HignSpeedUrls.value.splice(indexToDelete, 1);
                HignSpeedSubUploadID.value.splice(indexToDelete, 1); // 同时删除 HignSpeedSubUploadID 中的元素
            }
            loading.value = false
            getLists()
        })
    }).catch(() => {
    });
}
// 删除图片
const deletHighSpeedImg = async (index, event) => {
    event.stopPropagation();
    await SignDelFile(HignSpeedSubUploadID.value[index]).then(res => {
        HignSpeedUrls.value.splice(index, 1);
        HignSpeedSubUploadID.value.splice(index, 1);
        proxy.$modal.msgSuccess(`删除成功`)
        getLists();
    })
}
// 获取文件的 md5 值
const generateMd5Key = (file) => {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = (e) => {
            const md5key = md5(e.target.result);
            resolve(md5key);
        };
        reader.onerror = reject;
        reader.readAsArrayBuffer(file);  // 读取文件的二进制内容
    });
};

// 在上传文件之前生成 md5key
const beforeUpload = async (file) => {
    try {
        const md5key = await generateMd5Key(file);
        uploadData.value.md5key = md5key;  // 将生成的md5key添加到上传数据中
        // console.log("MD5 Key:", md5key,uploadData.value);
        return true;  // 返回true继续上传
    } catch (error) {
        return false;  // 返回false阻止上传
    }
};

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
    //  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (res, file, fileList) => {
    uploadData.value.md5key = '';
    fileList.value = []; // 清空上传的文件列表
    // 获取列表
    getLists();
};
const closewebSocketService = () => {
  if(webSocketService){
    CloseCameraBtn();
    // webSocketService.close()
  }
}
defineExpose({closewebSocketService})
function scheduleRender() {
    // 如果已经在渲染或队列为空，则跳过
    if (isRendering || frameQueue.length === 0) return;
    
    const now = performance.now();
    const elapsed = now - lastRenderTime;
    
    // 如果还没到下一帧的渲染时间，延迟执行
    if (elapsed < frameInterval) {
        if (animationFrameId) {
            cancelAnimationFrame(animationFrameId);
        }
        animationFrameId = requestAnimationFrame(() => {
            scheduleRender();
        });
        return;
    }
    
    // 执行渲染
    processRender();
}

// 新增的处理渲染函数
function processRender() {
    if (isRendering || frameQueue.length === 0) return;
    
    isRendering = true;
    const blob = frameQueue.shift();
    lastRenderTime = performance.now();
    
    // 使用Blob创建对象URL
    const url = URL.createObjectURL(blob);
    const img = new Image();
    
    img.onload = () => {
        if (canvasCtx.value) {
            canvasCtx.value.clearRect(0, 0, videoCanvas.value.width, videoCanvas.value.height);
            canvasCtx.value.drawImage(
                img, 
                0, 0, 
                videoCanvas.value.width, 
                videoCanvas.value.height
            );
        }
        
        // 清理资源
        URL.revokeObjectURL(url);
        isRendering = false;
        
        // 检查是否有新帧需要处理
        if (frameQueue.length > 0) {
            scheduleRender();
        }
    };
    
    img.onerror = (e) => {
        console.error("图片加载失败:", e);
        URL.revokeObjectURL(url);
        isRendering = false;
        
        // 即使出错也继续处理下一帧
        if (frameQueue.length > 0) {
            scheduleRender();
        }
    };
    img.src = url;
}
// 统一的清理函数
const cleanup = () => {
  CloseCameraBtn();
  if (animationFrameId) {
    cancelAnimationFrame(animationFrameId);
    animationFrameId = null; // 重置为null
  }
  frameQueue = [];
  if (webSocketService) {
    // webSocketService.close();
    webSocketService = null; // 重置为null
  }
};

// 组件卸载前的处理
onBeforeUnmount(() => {
  cleanup();
});

onUnmounted(() => {
  window.removeEventListener('beforeunload', cleanup);
});

</script>
<style scoped>
:deep().el-table__header {
    width: 100% !important;
}
</style>